/**
* @desc:  人员管理-添加人员，通过摄像头拍照
* @author qiankui
* @date 2023-9-13 14:37:06
*/
<template>
    <div>
        <el-dialog append-to-body :close-on-click-modal="false" :visible="imageCollectionFlag" class="zdy-dialog"
                   width="490px" height="380px" :title="$t('acquisition')"
                   :before-close="handleCloseDialog">

            <!--视频异常时显示的提示语-->
            <div v-if="cameraErrMsg" class="errorView" style="">
                <div v-if="cameraErrMsg=='NotFoundError'">
                    <!--我们找不到你的相机-->
                    <p style="font-weight: 700;font-size: 20px;margin-bottom: 20px">{{this.i18n.t("We can't find your camera")}}</p>
                    <p style="line-height: 25px">{{this.i18n.t("Device name not found containing")}} {{currentCamera.searchStr}} {{this.i18n.t("Camera for")}}<br>
                        <!--请检查以确保它已正确连接并安装，且未被防病毒软件阻止，并且你的摄像头驱动程序是最新的。如果你的电脑上有物理开关或按钮用于摄像头，请确保它已打开。-->
                        {{this.i18n.t("camera1")}}
                    </p>
                    <!--重试-->
                    <el-button @click="openCamera" style="margin-top: 50px">{{this.i18n.t("retry")}}</el-button>
                </div>
                <div v-if="cameraErrMsg=='NotReadableError'">
                    <!--关闭其他应用-->
                    <p style="font-weight: 700;font-size: 20px;margin-bottom: 20px">{{this.i18n.t("Close other apps")}}</p>
                    <!--似乎其他应用正在使用相机。-->
                    <p>{{this.i18n.t("It seems that other applications are using cameras")}}</p>
                    <el-button @click="openCamera" style="margin-top: 50px">{{this.i18n.t("retry")}}</el-button>
                </div>
            </div>
            <!--视频加载中loading动画-->
            <i v-if="cameraLoading" style="color: #fff;position: absolute;left: 180px;top: 195px;font-size: 30px" class="el-icon-loading"></i>
            <!--视频显示区域-->
            <video autoplay ref="video" id='video'></video>
            <!--摄像头名称-->
            <p style="color: #fff;margin-top: 10px">{{currentCamera.name}}</p>
            <!--拍照按钮-->
            <el-tooltip class="item" effect="light" :content="$t('take picture')" placement="top-start">
                <el-button @click="snapFn" :disabled="!snap" :loading="snapLoading" class="cameraView" style="font-size: 25px" icon="el-icon-camera"
                           circle></el-button>
            </el-tooltip>

            <!--拍照后显示大图的弹窗，在此弹窗内确定是重拍还是完成此次拍照-->
            <el-dialog :show-close="false" @close="closePreview" append-to-body :visible.sync="picViewFlag">
                <!--<img :src="" alt="">-->
                <el-image
                        :src="picViewSrc"
                        fit="contain"></el-image>

                <br>
                <br>
                <div class="footBtnBox">
                    <!--返回重新拍照-->

                    <el-tooltip size="small" class="item" effect="dark" :content="$t('Return to retake photos')" placement="top-start">
                        <el-button type="handle" @click="calcelFn">{{this.i18n.t('retake')}}</el-button>
                    </el-tooltip>


                    <!--保存-->
                    <!--使用这张照片-->
                    <el-tooltip size="small" class="item" effect="dark" :content="$t('Use this photo')" placement="top-start">
                        <el-button @click="save" :loading="saveLoading" type="primary">
                            {{this.i18n.t('complete')}}
                        </el-button>
                    </el-tooltip>

                </div>
            </el-dialog>

            <!--利用canvas截图区域，显示在屏幕之外-->
            <canvas :width="currentCamera.width" :height="currentCamera.height" ref="outputCanvas"
                    id="outputCanvas"></canvas>
        </el-dialog>
    </div>
</template>

<script>
    import {
        fileFiletobase64
    } from "@/api/pcmj/zzxx";
    export default {
        name: "imageCollection",
        props: {
            tabsIndex: {
                type: Number,
                default: 0
            },
            picIndex: {
                type: Number,
                default: 0
            },
            imageCollectionFlag: {
                type: Boolean,
                default: false
            },
        },
        data() {
            return {
                snapLoading:false,
                cameraLoading:true,
                cameraErrMsg:'',
                snap: false,
                cameraConfig: [
                    {
                        width: 1920,
                        height: 1080,
                        searchStr: 'Face_Camera',
                        // 开发阶段使用的相机名（发布后使用上面的名字）
                        // searchStr: 'Logi C270 HD WebCam',
                        desc: '人脸摄像头',
                        deviceId:null,
                        name:null,
                        // 未检测到人脸摄像头
                        errMsg: this.i18n.t("No facial camera detected")
                    },
                    {
                        width: 2592,
                        height: 1944,
                        // 正式的虹膜相机名
                        searchStr: 'Iris_Camera',
                        // 开发阶段使用的相机名（发布后使用上面的名字）
                        // searchStr: 'Logi C270 HD WebCam',
                        desc: '虹膜摄像头',
                        deviceId:null,
                        name:null,
                        // 未检测到虹膜摄像头
                        errMsg: this.i18n.t("No iris camera detected"),
                    },
                    {
                        width: 2592,
                        height: 1944,
                        searchStr: 'Palm Vein Collector',
                        desc: '掌静脉摄像头',
                        deviceId:null,
                        name:null,
                        // 未检测到掌静脉摄像头
                        errMsg: this.i18n.t("No palm vein cameras detected")

                    },
                ],
                fileList: [],
                dialogImageUrl: '',
                dialogVisible: false,
                currentCamera: {
                    deviceId: null,
                    width: null,
                    height: null,
                    errMsg:null,
                    name:null,
                    searchStr:null
                },
                backcontext: null,
                videoRefs: null,
                outPutRefs: null,
                picViewFlag: false,
                saveLoading: false,
                picViewSrc: null
            }
        },
        mounted() {
          // 关闭摄像头
          this.stopNavigator()
            this.$nextTick(async () => {
                console.log('tabsIndex,picIndex',this.tabsIndex, this.picIndex);

                this.videoRefs = this.$refs.video
                this.outPutRefs = this.$refs.outputCanvas
                this.backcontext = this.outPutRefs.getContext('2d')
                this.openCamera()
            })

        },
        methods: {
            calcelFn(){
                this.closePreview()
            },
            async save(){
                this.saveLoading=true

                this.$emit('setPicFn',{
                    tabsIndex:this.tabsIndex,
                    picIndex:this.picIndex,
                    showBase64Pic:this.picViewSrc
                })
                this.saveLoading=false
                this.handleCloseDialog()
            },
            // 将本地文件转成Base64
            async fileFiletobase64(filePath) {
                let res = await fileFiletobase64({filePath: filePath});
                return res
            },
            // 拍照
            photograph() {
                var type = this.tabsIndex
                var img = this.outPutRefs.toDataURL("1.jpg", 'image/octet-stream')
                this.picViewSrc = img
                this.picViewFlag = true
                this.snapLoading=false
            },
            // 关闭图片预览弹窗
            closePreview() {
                this.picViewFlag = false
                this.picViewSrc = null
            },
            snapFn() {
                this.snapLoading=true
                console.log('拍照');

                setTimeout(()=>{
                    this.photograph()
                },100)


            },
            // 文件状态改变时的钩子
            fileChange(file, fileList) {
                this.file = file.raw;
                if (fileList.length > 0) {
                    this.fileList = [fileList[fileList.length - 1]]; // 获取最后一次选择的文件
                }
            },
            // 关闭摄像头
            stopNavigator() {
                if(this.videoRefs&&this.videoRefs.srcObject!=null){
                    console.log('关闭回调',this.videoRefs.srcObject);
                    // debugger
                    this.videoRefs.srcObject.getTracks()[0].stop()
                    console.log('自动关闭成功*********************');
                }else{
                    console.log('自动关闭失败');
                }

            },
            // 关闭拍照界面弹窗
            handleCloseDialog() {
                this.$emit('update:imageCollectionFlag', false)
                // 关闭摄像头
                this.stopNavigator()
            },
            handleRemove(file, fileList) {
                console.log(file, fileList);
            },
            handlePictureCardPreview(file) {
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
            },
            draw() {
                var type = this.tabsIndex
                this.backcontext.drawImage(this.videoRefs, 0, 0, this.outPutRefs.width, this.outPutRefs.height)
                try {
                    this.backcontext.drawImage(this.videoRefs, 0, 0, this.outPutRefs.width, this.outPutRefs.height)
                } catch (e) {
                    if (e.name == "NS_ERROR_NOT_AVAILABLE") {
                        return setInterval(this.draw, 200)
                    } else {
                        throw e
                    }
                }
                setTimeout(this.draw, 500)
            },
            success(stream) {
                var type = this.tabsIndex
                // debugger
                this.videoRefs.srcObject = stream
                this.draw()
                // 摄像头开启成功
                this.W.$tips('success', this.i18n.t('Camera enabled successfully'))
                this.snap = true
                this.cameraLoading = false
                this.cameraErrMsg=""
            },
            error(err) {
                console.log('失败回调',err.name);
                this.snap = false
                this.cameraLoading = false
                this.cameraErrMsg = err.name
                // 摄像头开启失败
                this.W.$tips("error", this.i18n.t("The camera failed to turn on!"));
            },
            NotFoundErrorFn(){
                this.snap = false
                this.cameraLoading = false
                this.cameraErrMsg='NotFoundError'
                this.W.$tips("error", this.currentCamera.errMsg);
            },
            // 打开摄像头
            openCamera() {
                var type = this.tabsIndex
                this.cameraErrMsg=""
                this.cameraLoading = true
                this.currentCamera={...this.cameraConfig[type]}
                console.log(257,this.currentCamera);

                navigator.mediaDevices.enumerateDevices({audio: false, video: true}).then(res => {
                    if (res.length) {
                        // 人脸模式（基本信息tab页）下，只调用除了虹膜、掌静脉的摄像头
                        if (type == 0) {
                          var palmLabel="Palm Vein Collector",
                              iris="Iris_Camera"
                            res.map((item,index) => {
                                if (item.label.toLowerCase()!=='intel virtual camera'&&item.kind == "videoinput" && item.label.toLowerCase().indexOf(palmLabel.toLowerCase()) == -1 && item.label.toLowerCase().indexOf(iris.toLowerCase()) == -1) {
                                    this.currentCamera.deviceId = item.deviceId
                                    this.currentCamera.name = item.label
                                }
                            })
                        } else {
                            for (var i=0;i<res.length;i++){
                                console.log(res[i].label);
                                if(res[i].kind=='videoinput'&&res[i].label.toLowerCase().indexOf(this.currentCamera.searchStr.toLowerCase())!== -1){
                                    this.currentCamera.deviceId = res[i].deviceId
                                    this.currentCamera.name = res[i].label
                                }
                            }
                        }
                        // this.currentCamera.deviceId = "cdd5d977e1eb7e45f1dc4943f7d61d606b1fe6e4cf118933dd8d71066bd0f62d"
                        console.log('被查找的相机信息', this.currentCamera);
                        console.log('摄像头列表', res);
                        if (this.currentCamera.deviceId == null) {
                            // 未找到相机
                            this.NotFoundErrorFn()
                            return
                        } else {
                            navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia
                            navigator.getUserMedia({
                                video: {
                                    optional: [
                                        {
                                            sourceId: this.currentCamera.deviceId
                                        },
                                        {minWidth: this.currentCamera.width},
                                        {minHeight: this.currentCamera.height},
                                        {maxWidth: this.currentCamera.width},
                                        {maxHeight: this.currentCamera.height}
                                    ]
                                },
                                audio: false
                            }, this.success, this.error)
                        }

                    } else {
                        // 未找到相机
                        this.NotFoundErrorFn()
                        // 无摄像头!
                        this.W.$tips("error", this.i18n.t("No cameras!"));
                    }
                })
            },
        }
    }
</script>

<style scoped>
    #video {
        width: 360px;
        height: 270px;
        background: #000;
        border-radius: 12px;
    }
    .errorView{
        width: 460px;
        height: 275px;
        position: absolute;
        background-color: #202020;
        text-align: center;
        color: #fff;
        z-index: 2
    }
    .cameraView {
        width: 60px;
        height: 60px;
        /*color: #000 !important;*/
        /*border-radius: 100%;*/
        /*border: 1px solid red;*/
        /*display: flex;*/
        /*justify-content: center;*/
        /*align-items: center;*/
        position: absolute;
        left: 400px;
        top: 180px;
        cursor: pointer;
    }

    .cameraView .el-icon-camera {
        /*color: #000 !important;*/
    }

    .cameraView:hover {
        /*color: #fff !important;*/
    }

    .cameraView:active {
        background-color: #969696;
    }

    ::v-deep .el-dialog__body, ::v-deep .el-dialog__header {
        background: #202020;
        border-bottom: none;
    }

    ::v-deep .el-dialog__title {
        color: #fff;
        font-weight: 400;
        font-size: 14px;
    }

    #outputCanvas {
        position: absolute;

        /*left: 0;*/
        /*top: 350px;*/

        left: -9999999999px;
        bottom: -9999999999999px;
    }
</style>
